from flask import Flask, request, jsonify
import requests
import json
import count_case
from get_sms_info import get_sms_info

app = Flask(__name__)


def send_to_dingtalk(content, phone_numbers):
    """
    发送钉钉消息
    :param content: 消息内容
    :param phone_numbers: 手机号码列表
    :return:
    """
    # 官方Webhook地址
    # webhook_url = "https://oapi.dingtalk.com/robot/send?access_token=07fa4fd40c1645e02eb1ad77f16c4d6618bbd6bf54b76184a5c492eea8f2ddaa"
    # webhook_url = "https://oapi.dingtalk.com/robot/send?access_token=6c51aa838a174cf57e13a94b2e69c985ab4b4f5150c59c5def5ab2bb0c7577aa"
    webhook_url = "https://oapi.dingtalk.com/robot/send?access_token=0aead052d81cff17647c44f48e6106686c34e6823da120e669cb80e80e48de18"
    payload = {
        "msgtype": "markdown",
        "markdown": {
            "title": "自动化测试报告",
            "text": content
        },
        "at": {
            "atMobiles": phone_numbers,
            "isAtAll": False
        }
    }
    print(content, phone_numbers)
    headers = {'Content-Type': 'application/json'}

    # 发送请求
    response = requests.post(webhook_url, data=json.dumps(payload), headers=headers)
    if response.json().get('errcode') != 0:
        print("发送失败:", response.text)


@app.route('/dingtalk/webhook', methods=['POST'])
def receive():
    data = request.json
    if data.get('msgtype') == 'text':
        user_msg = data['text']['content']  # 用户发送的文本
        m, p = count_case.count_case(user_msg)
        # 转发到钉钉官方Webhook
        send_to_dingtalk(m, p)
        return jsonify({"status": "success"})
    return jsonify({"error": "Unsupported message type"}), 400


@app.route('/getSmsCode', methods=['GET'])
def get_sms_code():
    return jsonify(get_sms_info(request.args.get('code'), request.args.get('smsCode')))


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8899)
